package com.example.lirisheng.springbootfinalexperiment.security;


import com.example.lirisheng.springbootfinalexperiment.entity.Authorities;
import com.example.lirisheng.springbootfinalexperiment.repositories.AuthoritiesRepository;
import com.example.lirisheng.springbootfinalexperiment.repositories.RoleAuthoritiesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.*;

/**
 * @author : DGUT.YE
 * @date : 2020/09/15
 * 根据用户请求数据的url 去找到该url所需要的权限 看用户是否具有这个权限
 * 这个类的作用仅仅是找到对应url 所需要的权限返回
 **/
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    AuthoritiesRepository authoritiesRepository;

    @Autowired
    RoleAuthoritiesRepository roleAuthoritiesRepository;
    /**
     * 请求地址 匹配工具
     */
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        Iterator<Authorities> authorities = authoritiesRepository.findAll().iterator();
        Set<String> roles = new HashSet<>();
        Authorities authorities1;
        while(authorities.hasNext()){
            authorities1=authorities.next();
            if (antPathMatcher.match(authorities1.getName(),requestUrl)){
                roles=roleAuthoritiesRepository.findRoleByAthorityId(authorities1.getId());
                System.out.println("该URL所需要的权限:："+roles);
                return SecurityConfig.createList((String []) roles.toArray(new String[roles.size()]));
            }
        }

        // 如果匹配不到路径呢？ 如果不给访问那就返回null处理 这里是你登录了 就给你访问 这里返回的仅仅是标记 让你知道这个url没有匹配上
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
